package com.iweb.education.teacher.servlet;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iweb.education.teacher.model.Teacher;
import com.iweb.education.teacher.service.TeacherService;
import com.iweb.education.teacher.service.TeacherServiceImp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("*.teacher")
public class TeacherServlet extends HttpServlet {

    TeacherService service = new TeacherServiceImp();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String path = req.getServletPath();
        System.out.println("path:"+path);
        switch (path){
            case "/login.teacher":
                login(req,resp);
                break;
            case "/selectInfo.teacher":
                selectInfo(req,resp);
                break;
            case "/selectByPage.teacher":
                selectByPage(req,resp);
                break;
            case "/getStudent.teacher":
                getStudent(req, resp);
                break;
            case "/updateStudent.teacher":
                updateStudent(req, resp);
                break;
            case "/deleteStudent.teacher":
                deleteStudent(req, resp);
                break;
            default:
                break;
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String username = req.getParameter("username");
        String password= req.getParameter("password");
        if(service.isLogin(username,password,req.getSession())){
            //登录成功
            resp.sendRedirect(req.getContextPath()+"/teacher/teacherMain.html");
        }else {
            resp.sendRedirect(req.getContextPath()+"/teacher/teacherLogin.html?isLogin=0");
        }
    }

    private void selectInfo (HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        Teacher teacher  =(Teacher) session.getAttribute("teacher");
        String json = JSONObject.toJSONString(teacher);
        System.out.println(json);
        resp.getWriter().print(json);
    }
    private void selectByPage (HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            // 获取分页参数
            int currentPage = req.getParameter("page") != null ?
                    Integer.parseInt(req.getParameter("page")) : 1;
            int pageSize = 5; // 每页显示5条记录

            // 调用service获取分页数据
            Map<String, Object> pageData = service.getStudentsByPage(currentPage, pageSize);
            // 转换为JSON返回
            String json = JSONArray.toJSONString(pageData);
            resp.getWriter().print(json);

        } catch (Exception e) {
            e.printStackTrace();

        }

    }

    private void getStudent(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        try {
            int sid = Integer.parseInt(req.getParameter("sid"));
            Student student = service.getStudentById(sid);
            out.write(JSONObject.toJSONString(student));
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            out.write(JSONObject.toJSONString(error));
        }
    }

    private void updateStudent(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            Student student = new Student();
            student.setSid(Integer.parseInt(req.getParameter("sid")));
            student.setSname(req.getParameter("sname"));
            student.setSsex(req.getParameter("ssex"));
            student.setSphone(req.getParameter("sphone"));
            student.setSage(Integer.parseInt(req.getParameter("sage")));
            student.setSadress(req.getParameter("sadress"));

            boolean success = service.updateStudent(student);
            result.put("success", success);

        } catch (Exception e) {
            result.put("success", false);
            result.put("error", e.getMessage());
        }

        out.write(JSONObject.toJSONString(result));
    }

    private void deleteStudent(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            int sid = Integer.parseInt(req.getParameter("sid"));
            boolean success = service.deleteStudent(sid);
            result.put("success", success);

        } catch (Exception e) {
            result.put("success", false);
            result.put("error", e.getMessage());
        }

        out.write(JSONObject.toJSONString(result));
    }
}


